import React, { useEffect, useState } from "react";
import { ListRawState } from "../../types";
import axios from "axios";
import {
  Table,
  Button,
  Space,
  Modal,
  message as antdMessage,
  Row,
  Col,
  Input,
  Divider,
} from "antd";
import "./style.css";
import { useNavigate } from "react-router-dom";
const List: React.FC = () => {
  const navigate = useNavigate();
  /********************************  列表渲染 **************************************/

  // 1. 容器
  const [list, setList] = useState<ListRawState[]>([]);
  // 2. 请求函数
  const fetchList = async () => {
    const resp = await axios.get("/api/list", {
      params: { value, type, min, max, sort },
    });
    setList(resp.data.data);
  };
  // 3. 副作用函数
  useEffect(() => {
    fetchList();
  }, []);
  /********************************  删除 **************************************/
  // 5. 单项删除
  const handleDelete = (id: string) => {
    // 5-1. 获取 id
    // 5-2. 二次确认
    Modal.confirm({
      title: "警告",
      content: "确定要删除该想数据吗？",
      onOk() {
        // 3. 删除操作
        axios.delete("/api/list", { params: { id } }).then((resp) => {
          antdMessage.success(resp.data.message);
          fetchList();
        });
      },
    });
  };
  // 7. 定义当前选中的id
  const [ids, setIds] = useState<string[]>([]);
  // 4. 表格列
  const columns = [
    {
      key: "1",
      title: ids.length ? (
        <Button type="primary" danger onClick={() => handleDeleteBySelected()}>
          选中删除
        </Button>
      ) : (
        "id"
      ),
      dataIndex: "id",
    },
    {
      key: "2",
      title: "电话",
      dataIndex: "tel",
    },
    {
      key: "3",
      title: "标题",
      dataIndex: "title",
    },
    {
      key: "4",
      title: "地址",
      dataIndex: "address",
    },
    {
      key: "5",
      title: "价格",
      dataIndex: `price`,
      render(text: string) {
        return "¥：" + text;
      },
    },
    {
      key: "6",
      title: "数量",
      dataIndex: "count",
    },
    {
      key: "66",
      title: "类型",
      dataIndex: "type",
    },
    {
      key: "7",
      title: "操作",
      dataIndex: "id",
      render(text: string, record: ListRawState) {
        return (
          <Space>
            <Button type="link" onClick={() => navigate("/detail/" + text)}>
              详情
            </Button>
            <Button
              type="primary"
              onClick={() => {
                setIsOpen(true);
                setModifyItem(record);
              }}
            >
              编辑
            </Button>
            <Button type="primary" danger onClick={() => handleDelete(text)}>
              删除
            </Button>
          </Space>
        );
      },
    },
  ];
  // 6. 选中删除
  const handleDeleteBySelected = () => {
    handleDelete(ids.join(","));
  };
  /********************************* 编辑 *********************************/
  // 7. 弹框张涛
  const [isOpen, setIsOpen] = useState(false);
  // 8. 状态数据
  const [modifyItem, setModifyItem] = useState<ListRawState>({
    id: "1",
    count: 2,
    price: 3,
    title: "4",
    address: "5",
    tel: 6,
    content: "7",
    type: "",
  });
  // 9. 确定修改
  const handleEdit = async () => {
    await axios.post("/api/list", modifyItem);
    fetchList();
  };
  /********************************** 模糊搜索 *****************************/
  // 10. 定义搜索数据
  const [value, setValue] = useState("");
  // 11. 查询函数
  const handleQuery = () => {
    fetchList();
  };
  /********************************** 类型搜索 *****************************/
  // 12. 类型数组
  const types = ["全部", "已发货", "已收货", "已签收", "已关闭", "待评价"];
  // 13. 类型数据
  const [type, setType] = useState("已关闭");
  /********************************** 价格区间 *****************************/
  const [min, setMin] = useState("");
  const [max, setMax] = useState("");
  /********************************** 价格排序 *****************************/
  const sortList = ["默认排序", "升序", "降序"];
  const [sort, setSort] = useState("默认排序");
  /********************************* 拖拽 **************************************/
  const onRow = (state: ListRawState[], setState: any, record: ListRawState) => ({
    draggable: true,
    style: { cursor: "move" },
    key: record.id,
    onDragStart: (ev: any) => {
      ev.dataTransfer.effectAllowed = "move";
      ev.dataTransfer.setData("text", ev.target.getAttribute("data-row-key"));
    },
    // onDragEnter: (ev: any) => {
    //   const nodes = ev.target.parentNode.childNodes;
    //   nodes.forEach(
    //     (item: any) => (item.style.borderTop = "2px dashed #1890ff")
    //   );
    // },
    // onDragLeave: (ev: any) => {
    //   const nodes = ev.target.parentNode.childNodes;
    //   nodes.forEach((item: any) => (item.style.borderTop = ""));
    // },
    onDrop: (ev: any) => {
      ev.preventDefault();
      ev.stopPropagation();
      console.log(record, state)
      const dragId = (ev.dataTransfer.getData("text"));

      const dragIndex = state.findIndex((item: any) => item.id === dragId); // 注意这里的id
      const dropIndex = state.findIndex((item: any) => item.id === record.id);

      console.log(dragIndex, dropIndex)
      const data = [...state].map((v, i) => {
        if(i === dragIndex) {
          return { ...record }
        }
        if(i === dropIndex) {
          return state[dragIndex]
        }
        return v
      });
      setState(data);
      // dropCol.childNodes.forEach((item: any) => (item.style.borderTop = ""));
    },
    onDragOver: (ev: any) => ev.preventDefault(),
  });
  return (
    <div className="content">
      <Row className="row">
        <Col span={2} style={{ textAlign: "right" }}>
          搜索：
        </Col>
        <Col span={20}>
          <Input.Search
            value={value}
            onChange={(e) => setValue(e.target.value.trim())}
            onSearch={() => handleQuery()}
          ></Input.Search>
        </Col>
      </Row>
      <Row className="row">
        <Col span={2} style={{ textAlign: "right" }}>
          类型：
        </Col>
        <Col span={20}>
          <Space>
            {types.map((v, i) => {
              return (
                <Button
                  onClick={() => setType(v)}
                  type={type === v ? "primary" : "default"}
                  key={i}
                >
                  {v}
                </Button>
              );
            })}
          </Space>
        </Col>
      </Row>
      <Row className="row">
        <Col span={2} style={{ textAlign: "right" }}>
          价格区间：
        </Col>
        <Col span={4}>
          <Input
            placeholder="请输入价格最小值"
            value={min}
            onChange={(e) => setMin(e.target.value)}
          ></Input>
        </Col>
        <Col span={2}>
          <Divider></Divider>
        </Col>
        <Col span={4}>
          <Input
            placeholder="请输入价格最大值"
            value={max}
            onChange={(e) => setMax(e.target.value)}
          ></Input>
        </Col>
      </Row>
      <Row className="row">
        <Col span={2} style={{ textAlign: "right" }}>
          价格排序：
        </Col>
        <Col span={20}>
          <Space>
            {sortList.map((v, i) => {
              return (
                <Button
                  onClick={() => setSort(v)}
                  type={sort === v ? "primary" : "default"}
                  key={i}
                >
                  {v}
                </Button>
              );
            })}
          </Space>
        </Col>
      </Row>
      <Row className="row">
        <Col span={2} style={{ textAlign: "right" }}></Col>
        <Col span={20}>
          <Space>
            <Button type="primary" onClick={() => handleQuery()}>
              查询
            </Button>
            <Button type="primary" danger>
              重置
            </Button>
          </Space>
        </Col>
      </Row>
      <Table
        dataSource={list}
        columns={columns}
     
        rowSelection={{
          onChange(selectKeys) {
            setIds(selectKeys as string[]);
          },
        }}
        pagination={{
          defaultPageSize: 5,
        }}
        onRow={(record) => onRow(list, setList,record)}
        rowKey={"id"}
      ></Table>
      <Modal
        open={isOpen}
        title="编辑"
        okText="确定"
        cancelText="取消"
        onOk={() => {
          setIsOpen(false);
          handleEdit();
        }}
        onCancel={() => setIsOpen(false)}
      >
        <Row className="row">
          <Col span={4}>id：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.id}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  id: e.target.value,
                })
              }
              disabled
            ></Input>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4}>电话：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.tel}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  tel: +e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4}>标题：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.title}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  title: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4}>地址：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.address}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  address: e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4}>价格：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.price}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  price: +e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
        <Row className="row">
          <Col span={4}>数量：</Col>
          <Col span={20}>
            <Input
              value={modifyItem.count}
              onChange={(e) =>
                setModifyItem({
                  ...modifyItem,
                  count: +e.target.value,
                })
              }
            ></Input>
          </Col>
        </Row>
      </Modal>
    </div>
  );
};

export default List;
